#include "../Include/Condition.h"
#include <time.h>
#include <errno.h>

CCondition::CCondition(CMutex &mutex) : m_mutex(mutex)
{
    pthread_cond_init(&m_cond, NULL);
}

CCondition::~CCondition()
{
    pthread_cond_destroy(&m_cond);
}

void CCondition::Wait()
{
    pthread_cond_wait(&m_cond, m_mutex.GetMutex());
}

void CCondition::Notify()
{
    pthread_cond_signal(&m_cond);
}

void CCondition::NotifyAll()
{
    pthread_cond_broadcast(&m_cond);
}

Bool CCondition::WaitForSeconds(Double seconds)
{
    struct timespec abstime;
    clock_gettime(CLOCK_REALTIME, &abstime);

    const Int64 kNanoSecondsPerSecond = 1000000000;
    Int64 nanoseconds = static_cast<Int64>(seconds * kNanoSecondsPerSecond);

    abstime.tv_sec += static_cast<time_t>((abstime.tv_nsec + nanoseconds) / kNanoSecondsPerSecond);
    abstime.tv_nsec = static_cast<long>((abstime.tv_nsec + nanoseconds) % kNanoSecondsPerSecond);

    return ETIMEDOUT == pthread_cond_timedwait(&m_cond, m_mutex.GetMutex() , &abstime);
}

